<template>
  <div class="search">
    <a-input-search
      v-model:value="value"
      placeholder="input search text"
      enter-button="Search"
      size="large"
      allow-clear
      @search="onSearch"
    />
    <a-button type="primary" size="large" @click="showModal">添加景点</a-button>
  </div>
  <div class="card-list">
    <ScenicCard
      v-for="(scenicVO, index) in scenicVOs"
      :key="scenicVO.id || index"
      :scenic="scenicVO"
      @click="showScenicInfo"
    />
  </div>

  <!-- 分页组件 -->
  <div class="pagination-container">
    <a-pagination
      v-model:current="pagination.current"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      :show-total="
        (total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
      "
      :show-size-changer="true"
      :show-quick-jumper="true"
      :page-size-options="['8', '16', '24', '32']"
      @change="handlePageChange"
      @showSizeChange="handlePageSizeChange"
    />
  </div>

  <!-- 添加景点模态框 -->
  <a-modal
    v-model:open="isModalVisible"
    title="添加景点"
    @cancel="handleCancel"
    :footer="null"
    width="800px"
  >
    <AddScenicForm @success="handleAddSuccess" @cancel="handleCancel" />
  </a-modal>

  <!-- 景点详情模态框 -->
  <a-modal
    v-model:open="isInfoModalVisible"
    title="景点详情"
    @cancel="handleInfoCancel"
    :footer="null"
    width="900px"
  >
    <ScenicInfo
      v-if="selectedScenic"
      :scenic-data="selectedScenic"
      @updated="handleScenicUpdated"
      @refresh="handleScenicRefresh"
      @deleted="handleScenicDeleted"
    />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { getListScenicVo } from '@/api/scenicController'
import { message } from 'ant-design-vue'
import AddScenicForm from '@/components/AddScenicForm.vue'
import ScenicInfo from '@/components/ScenicInfo.vue'
import ScenicCard from '@/components/ScenicCard.vue'

const scenicVOs = ref(<API.ScenicVO[]>[])
const value = ref<string>('')
const isModalVisible = ref<boolean>(false)
const isInfoModalVisible = ref<boolean>(false)
const selectedScenic = ref<API.ScenicVO | null>(null)

// 分页相关状态
const pagination = ref({
  current: 1,
  pageSize: 8,
  total: 0,
})

const fetchData = async (params: API.getListScenicVOParams = {}) => {
  try {
    const requestParams = {
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
      ...params,
    }

    console.log('请求参数:', requestParams)
    const res = await getListScenicVo(requestParams)
    console.log('获取到的分页数据:', res.data)

    if (res.data.code === 200 && res.data.data) {
      const pageData = res.data.data
      scenicVOs.value = pageData.records ?? []
      pagination.value.total = parseInt(pageData.total ?? '0')
      pagination.value.current = parseInt(pageData.current ?? '1')
      pagination.value.pageSize = parseInt(pageData.size ?? '8')

      console.log('解析后的景点列表:', scenicVOs.value)
      console.log('分页信息:', pagination.value)

      // 检查每个景点的 ID
      scenicVOs.value.forEach((scenic, index) => {
        console.log(`景点 ${index}:`, {
          id: scenic.id,
          idType: typeof scenic.id,
          scenicName: scenic.scenicName,
        })
      })
    }
  } catch (error) {
    console.error('获取景点数据失败:', error)
    message.error('获取景点数据失败')
  }
}

const onSearch = async (searchValue: string) => {
  pagination.value.current = 1 // 搜索时重置到第一页
  await fetchData({ scenicName: searchValue })
}

// 显示添加景点模态框
const showModal = () => {
  isModalVisible.value = true
}

// 显示景点详情模态框
const showScenicInfo = (scenic: API.ScenicVO) => {
  console.log('点击了景点卡片:', scenic)
  console.log('景点ID:', scenic.id)
  console.log('景点名称:', scenic.scenicName)

  selectedScenic.value = scenic
  console.log('selectedScenic 设置为:', selectedScenic.value)

  isInfoModalVisible.value = true
  console.log('isInfoModalVisible 设置为:', isInfoModalVisible.value)
}

// 点击取消或遮罩层关闭添加模态框
const handleCancel = () => {
  isModalVisible.value = false
}

// 点击取消或遮罩层关闭详情模态框
const handleInfoCancel = () => {
  isInfoModalVisible.value = false
  selectedScenic.value = null
}

// 处理添加景点成功事件
const handleAddSuccess = async () => {
  console.log('景点添加成功，正在刷新数据...')
  isModalVisible.value = false // 关闭模态框
  await fetchData() // 重新获取数据
  message.success('数据已刷新！')
}

// 处理景点更新事件
const handleScenicUpdated = async (updatedScenic: API.ScenicVO) => {
  console.log('景点更新成功，正在刷新数据...')

  // 更新本地列表中的景点数据
  const index = scenicVOs.value.findIndex((scenic) => scenic.id === updatedScenic.id)
  if (index !== -1) {
    scenicVOs.value[index] = updatedScenic
  }

  // 更新选中的景点数据
  selectedScenic.value = updatedScenic

  message.success('景点信息已更新！')
}

// 处理景点刷新请求（从后端重新获取最新数据）
const handleScenicRefresh = async (scenicId: string) => {
  try {
    console.log('🔄 开始刷新景点数据，ID:', scenicId)

    // 重新获取完整的景点列表
    await fetchData()

    // 从更新后的列表中找到对应的景点
    const updatedScenic = scenicVOs.value.find((scenic) => scenic.id?.toString() === scenicId)
    if (updatedScenic) {
      selectedScenic.value = updatedScenic
      console.log('✅ 景点数据刷新成功')
      message.success('景点信息已更新！')
    } else {
      console.warn('⚠️ 刷新后未找到对应景点')
    }
  } catch (error) {
    console.error('❌ 刷新景点数据失败:', error)
    message.error('刷新失败，请稍后再试')
  }
}

// 处理景点删除事件
const handleScenicDeleted = async (scenicId: number) => {
  console.log('景点删除成功，ID:', scenicId)

  // 关闭详情模态框
  isInfoModalVisible.value = false
  selectedScenic.value = null

  // 重新获取数据
  await fetchData()

  message.success('景点删除成功！')
}

// 处理分页变化
const handlePageChange = (page: number, pageSize: number) => {
  console.log('分页变化:', { page, pageSize })
  pagination.value.current = page
  pagination.value.pageSize = pageSize
  fetchData({ scenicName: value.value || undefined })
}

// 处理每页条数变化
const handlePageSizeChange = (current: number, size: number) => {
  console.log('每页条数变化:', { current, size })
  pagination.value.current = 1 // 改变每页条数时重置到第一页
  pagination.value.pageSize = size
  fetchData({ scenicName: value.value || undefined })
}

fetchData()
</script>

<style scoped>
.card-list {
  margin: 0 auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  max-width: calc((280px + 24px) * 4 - 24px);
}

.search {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 36px auto;
  gap: 20px;
  max-width: calc((280px + 24px) * 4 - 24px);
  padding: 0 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 32px 0;
  padding: 16px 0;
}
</style>
